package cn.mw.cmdb.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.mw.cmdb.entity.*;
import cn.mw.cmdb.entity.cloudWisdom.CloudWisdomReportHistoryInfo;
import cn.mw.cmdb.entity.cloudWisdom.CloudWisdomReportHistoryStatusCountInfo;
import cn.mw.cmdb.entity.dto.InventoryHistoryCountDTO;
import cn.mw.cmdb.enums.InventoryCheck;
import cn.mw.cmdb.enums.WorkStateCountEnum;
import cn.mw.cmdb.enums.WorkStateEnum;
import cn.mw.cmdb.mongoMapper.InventoryWorkAssetsMapper;
import cn.mw.cmdb.mongoMapper.InventoryWorkInfoMapper;
import cn.mw.cmdb.param.*;
import cn.mw.cmdb.service.InventoryWorkInfoService;
import cn.mw.cmdb.service.ModelService;
import cn.mw.cmdb.util.CMDBTool;
import cn.mw.cmdb.view.ViewConvertContext;
import cn.mw.cmdb.view.ViewManager;
import cn.mw.components.mongodb.entity.*;
import cn.mw.components.mongodb.exception.BusinessException;
import cn.mw.components.mongodb.page.MWPage;
import cn.mw.components.mongodb.tool.CriteriaWrapper;
import cn.mw.microMonitorCommon.api.user.MwUserApi;
import cn.mw.microMonitorCommon.entity.userDTO.OrgDTO;
import cn.mw.microMonitorCommon.enums.FinanceReportLogStatusEnum;
import cn.mw.microMonitorCommon.security.dto.MwUser;
import cn.mw.microMonitorCommon.security.utils.SecurityUtils;
import cn.mw.microMonitorCommon.util.DateUtils;
import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static cn.mw.cmdb.util.BaseUtil.getNowLocalTime;
import static cn.mw.cmdb.util.CMDBTool.getFieldName;
import static cn.mw.cmdb.util.ValConvertUtil.strValueConvert;

/**
 * @Author shenwenyi
 * @Date 2024/4/26 15:50
 * @PackageName:cn.mw.cmdb.service.impl
 * @ClassName: InventoryWorkInfoServiceImpl
 * @Description: TODD
 * @Version 1.0
 */
@Slf4j
public class InventoryWorkInfoServiceImpl extends ModelBaseServiceImpl<InventoryWorkInfo, Object> implements InventoryWorkInfoService {

    public static final String ID = "inventory";
    /**
     * 设备品牌
     */
    public static final String MW_ASSETBRAND = "mw_assetBrand";


    /**
     * 设备序列号
     */
    public static final String MW_PRODUCT_ID = "mw_product_id";
    /**
     * 资产编码
     */
    public static final String MW_ASSET_CODING = "mw_asset_coding";
    /**
     * 资产状态
     */
    public static final String MW_ASSET_STATUS = "mw_asset_status";

    /**
     * 规则型号
     */
    public static final String MW_SPECIFICATIONS = "mw_specifications";

    private InventoryWorkInfoMapper inventoryWorkInfoMapper;

    private CmdbServiceManage cmdbServiceManage;
    private ViewManager viewManager;
    private InventoryWorkAssetsMapper inventoryWorkAssetsMapper;

    private static ThreadLocal<List<AddAndUpdInstanceContext>> addAndUpdInstanceContextThreadLocal = new ThreadLocal<>();
    private MwUserApi userApi;
    private MessageSource messageSource;

    public void removeAddAndUpdInstanceContextThreadLocal() {
        addAndUpdInstanceContextThreadLocal.remove();
    }

    public InventoryWorkInfoServiceImpl(InventoryWorkInfoMapper inventoryWorkInfoMapper,
                                        CmdbServiceManage cmdbServiceManage,
                                        MwUserApi userApi,
                                        ViewManager viewManager,
                                        InventoryWorkAssetsMapper inventoryWorkAssetsMapper,
                                        MessageSource messageSource) {
        this.inventoryWorkInfoMapper = inventoryWorkInfoMapper;
        this.cmdbServiceManage = cmdbServiceManage;
        this.userApi = userApi;
        this.viewManager = viewManager;
        this.inventoryWorkAssetsMapper = inventoryWorkAssetsMapper;
        this.messageSource = messageSource;
    }

    @Override
    public InventoryWorkInfo genObject() {
        return new InventoryWorkInfo();
    }

    @Override
    Object doAdd(InventoryWorkInfo param) throws Exception {
        Date nowLocalTime = getNowLocalTime();
        MwUser user = SecurityUtils.getUser();
        String loginName = user.getUsername();
        param.setCreator(loginName);
        param.setModifier(loginName);
        param.setCreateDate(nowLocalTime);
        param.setModificationDate(nowLocalTime);
        param.setWorkState(WorkStateEnum.PENDING.getCode());
        inventoryWorkInfoMapper.save(param);
        List<String> assetsIdList = param.getAssetsIdList();
        List<InventoryWorkAssets> list = new ArrayList<>();
        assetsIdList.forEach(id -> {
            InventoryWorkAssets workAssets = new InventoryWorkAssets();
            workAssets.setInventoryWorkInfoId(param.getId());
            workAssets.setAssetsId(id);
            workAssets.setCount(1);
            workAssets.setInventoryCount(null);
            workAssets.setCreator(loginName);
            workAssets.setCreateDate(nowLocalTime);
            workAssets.setModifier(loginName);
            workAssets.setModificationDate(nowLocalTime);
            list.add(workAssets);
        });
        ModelService modelService = cmdbServiceManage.getModelService(InventoryWorkAssetsServiceImpl.ID);
        modelService.batchAdd(list);
        return true;
    }

    @Override
    boolean doUpdate(InventoryWorkInfo param) throws Exception {
        MwUser user = SecurityUtils.getUser();
        String loginName = user.getUsername();
        param.setModifier(loginName);
        param.setModificationDate(getNowLocalTime());
        Query query = new Query(CriteriaWrapper.where(InventoryWorkInfo::getId).is(param.getId()));
        Update update = new Update();
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getWorkName), param.getWorkName());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getProcessId), param.getProcessId());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getDescribe), param.getDescribe());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getPlannedStartTime), param.getPlannedStartTime());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getPlannedEndTime), param.getPlannedEndTime());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getImgUrl), param.getImgUrl());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getPrincipal),param.getPrincipal());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getModifier), param.getModifier());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getModificationDate), param.getModificationDate());
        CMDBTool.updateFirst(inventoryWorkInfoMapper, query, update);
        return true;
    }

    @Override
    boolean doRemove(InventoryWorkInfo param) throws Exception {
        return false;
    }

    @Override
    Object doBatchAdd(Object params) throws Exception {
        return null;
    }

    @Override
    boolean doBatchUpdate(Object params) throws Exception {
        return false;
    }

    @Override
    InventoryWorkInfo doSelectById(Object params) throws Exception {
        InventorySearchParam param = (InventorySearchParam) params;
        InventoryWorkInfo info = inventoryWorkInfoMapper.findById(param.getId());
        info.setAppPlannedEndTime(info.getPlannedEndTime());
        info.setAppPlannedStartTime(info.getPlannedStartTime());
        List<String> assetsIdList = info.getAssetsIdList();
        if (CollUtil.isNotEmpty(assetsIdList)) {
            InstanceServiceImpl instanceService = (InstanceServiceImpl) cmdbServiceManage.getModelService(InstanceServiceImpl.ID);
            InventoryWorkAssetsServiceImpl workAssetsService = (InventoryWorkAssetsServiceImpl) cmdbServiceManage.getModelService(InventoryWorkAssetsServiceImpl.ID);
            InstanceSearchParam instanceSearchParam = new InstanceSearchParam();
            instanceSearchParam.setInstanceIds(assetsIdList);
            instanceSearchParam.setIgnoreDataAuth(true);
            List<InstanceInfoExtend> instanceInfoExtends = instanceService.aggregateList(instanceSearchParam);
            InventoryWorkAssetsParam inventoryWorkAssetsParam = new InventoryWorkAssetsParam();
            inventoryWorkAssetsParam.setInventoryWorkInfoId(info.getId());

            List<InventoryWorkAssets> inventoryWorkAssets = workAssetsService.selectList(inventoryWorkAssetsParam);
            Map<String, InstanceInfoExtend> instanceInfoExtendMap = instanceInfoExtends.stream().collect(Collectors.toMap(InstanceInfoExtend::getId, Function.identity()));

            List<Long> userIds = instanceInfoExtends.stream().map(DataAuth::getUsers).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList());
            List<Long> orgIds = instanceInfoExtends.stream().map(DataAuth::getOrgIds).filter(Objects::nonNull).flatMap(Collection::stream).collect(Collectors.toList());
            List<Long> principalId = info.getPrincipal().stream().map(Long::valueOf).collect(Collectors.toList());
            userIds.addAll(principalId);
            Map<Long, MwUser> userMap = new HashMap<>();
            Map<Long, OrgDTO> orgMap = new HashMap<>();
            if (CollUtil.isNotEmpty(userIds)) {
                userMap = Optional.ofNullable(userApi.getUsersByUserIds(userIds))
                        .orElse(Collections.emptyList())
                        .stream()
                        .collect(Collectors.toMap(MwUser::getId, Function.identity()));
            }
            if (CollUtil.isNotEmpty(orgIds)) {
                orgMap = Optional.ofNullable(userApi.getOrgListByOrgIds(orgIds))
                        .orElse(Collections.emptyList())
                        .stream()
                        .collect(Collectors.toMap(OrgDTO::getId, Function.identity()));
            }
            Map<Long, MwUser> mwUserMap = userMap;
            String principalNames = Optional.ofNullable(principalId)
                    .map(users -> users.stream().map(userId -> Optional.ofNullable(mwUserMap.get(userId)).map(MwUser::getNickName).orElse(null)).filter(Objects::nonNull).collect(Collectors.joining(","))).orElse("");
            info.setPrincipalNames(principalNames);
            for (InventoryWorkAssets workAsset : inventoryWorkAssets) {
                String assetId = workAsset.getAssetsId();
                InstanceInfoExtend matchingInstance = instanceInfoExtendMap.get(assetId);

                if (matchingInstance != null) {
                    Object brand = matchingInstance.getData().get(MW_ASSETBRAND);
                    Object productId = matchingInstance.getData().get(MW_PRODUCT_ID);
                    Object assetCoding = matchingInstance.getData().get(MW_ASSET_CODING);
                    Object assetStatus = matchingInstance.getData().get(MW_ASSET_STATUS);
                    Object specifications = matchingInstance.getData().get(MW_SPECIFICATIONS);
                    Map<Long, MwUser> finalUserMap = userMap;
                    String principal = Optional.ofNullable(matchingInstance.getUsers())
                            .map(users -> users.stream().map(userId -> Optional.ofNullable(finalUserMap.get(userId)).map(MwUser::getNickName).orElse("")).collect(Collectors.joining(","))).orElse("");
                    Map<Long, OrgDTO> finalOrgMap = orgMap;
                    String orgName = Optional.ofNullable(matchingInstance.getOrgIds())
                            .map(orgIdsList -> orgIdsList.stream().map(orgId -> Optional.ofNullable(finalOrgMap.get(orgId)).map(OrgDTO::getOrgName).orElse("")).collect(Collectors.joining(","))).orElse("");
                    workAsset.setInstanceName(matchingInstance.getInstanceName());
                    workAsset.setModelGroupName(matchingInstance.getModelGroupName());
                    workAsset.setBrand(ObjectUtil.isNotEmpty(brand) ? JSON.toJSONString(brand) : "");
                    workAsset.setProductId(ObjectUtil.isNotEmpty(productId) ? String.valueOf(productId) : "");
                    workAsset.setUsers(matchingInstance.getUsers());
                    workAsset.setPrincipal(principal);
                    workAsset.setOrgIds(matchingInstance.getOrgIds());
                    workAsset.setOrgName(orgName);
                    workAsset.setAssetCoding(ObjectUtil.isNotEmpty(assetCoding) ? String.valueOf(assetCoding) : "");
                    workAsset.setAssetStatus(ObjectUtil.isNotEmpty(assetStatus) ? String.valueOf(assetStatus) : "");
                    workAsset.setSpecifications(ObjectUtil.isNotEmpty(specifications) ? String.valueOf(specifications) : "");
                }
            }

            int today=(int)inventoryWorkAssets.stream().filter(obj ->obj.getInventoryCount()!=null && DateUtils.formatDate(obj.getModificationDate()).equals(DateUtils.nowDate())).count();
            int tobe=(int)inventoryWorkAssets.stream().filter(obj ->obj.getInventoryCount()==null ).count();
            Map<String, Integer> status2CountMap = new LinkedHashMap<>();
            int size = inventoryWorkAssets.size();
            int inventoried=size- tobe;
            status2CountMap.put(WorkStateCountEnum.TOBE.getDesc(),tobe);
            status2CountMap.put(WorkStateCountEnum.TODAY.getDesc(),today);
            status2CountMap.put(WorkStateCountEnum.INVENTORIED.getDesc(),inventoried );
            status2CountMap.put(WorkStateCountEnum.TOTAL.getDesc(),size);
            //计算百分百
            if(size!=0){
                info.setInventoryProgress((inventoried*100/size));
            }
            MWPage<InventoryWorkAssets> page = (MWPage) viewManager.getListViewObject(inventoryWorkAssets, InventoryWorkAssets.class, param, null);
            info.setInventoryWorkAssetsList(page);
            info.setStatus2CountMap(status2CountMap);
        }
        return info;
    }

    @Override
    List<InventoryWorkInfo> doSelectList(Object param) throws Exception {
        InventorySearchParam searchParam = (InventorySearchParam) param;
        searchParam.convert();
        Date currentDate = DateUtils.date();
        Query query = new Query(CriteriaWrapper.where(InventoryWorkInfo::getPlannedEndTime).lt(currentDate));
        query.addCriteria(CriteriaWrapper.where(InventoryWorkInfo::getWorkState).is(WorkStateEnum.PENDING.getCode()));
        Update update = new Update();
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getWorkState), WorkStateEnum.EXCEED.getCode());
        inventoryWorkInfoMapper.updateMulti(query, update);
        Criteria criteria = genCriteria(searchParam);
        searchParam.sort();
        searchParam.setIgnoreDataAuth(true);
        List<InventoryWorkInfo> infos = CMDBTool.aggregateAuthorizedList(InventoryWorkInfo.class, inventoryWorkInfoMapper, criteria, searchParam);
        List<Long> allPrincipals = infos.stream()
                .flatMap(info -> info.getPrincipal().stream().map(userId -> Long.valueOf(userId)))
                .collect(Collectors.toList());
        List<MwUser> users = userApi.getUsersByUserIds(allPrincipals);
        Map<Long, String> userMap = users.stream().collect(Collectors.toMap(MwUser::getId, MwUser::getNickName));
        infos.forEach(info -> {
            List<String> collect = info.getPrincipal().stream().map(principal -> userMap.get(Long.valueOf(principal)))
                    .collect(Collectors.toList());
            info.setPrincipal(collect);
        });
        return infos;
    }

    @Override
    boolean doBatchRemove(Object params) throws Exception {
        return false;
    }

    @Override
    public List<InventoryWorkInfo> selfInventory(InventorySearchParam param) throws Exception {
        List<Criteria> criteriaList = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();
        param.setPrincipal(strValueConvert(userId));
        param.setIgnoreDataAuth(true);
        param.convert();
        param.sort();
        Criteria criteria = genCriteria(param);
        criteriaList.add(criteria);
        if(null != param.getInventoryType()){
            Criteria criteria2 = new Criteria(CMDBTool.getFieldName(InventoryWorkInfo::getInventoryType)).is(param.getInventoryType());
            criteriaList.add(criteria2);
        }
        Criteria searchCriteria = new Criteria().andOperator(criteriaList);
        List<InventoryWorkInfo> list = CMDBTool.selectAuthorizedList(InventoryWorkInfo.class,inventoryWorkInfoMapper, searchCriteria, param);
        List<Long> userIds = list.stream()
                .flatMap(info -> info.getPrincipal().stream().map(id -> Long.valueOf(id)))
                .collect(Collectors.toList());
        List<MwUser> usersByUserIds = userApi.getUsersByUserIds(userIds);
        Map<Long, String> userMap = usersByUserIds.stream().collect(Collectors.toMap(MwUser::getId, MwUser::getNickName));
        list.forEach(info -> {
            List<String> collect = info.getPrincipal().stream().map(principal -> userMap.get(Long.valueOf(principal)))
                    .collect(Collectors.toList());
            info.setPrincipal(collect);
        });
        InventoryWorkAssetsServiceImpl workAssetsService = (InventoryWorkAssetsServiceImpl) cmdbServiceManage.getModelService(InventoryWorkAssetsServiceImpl.ID);

        List<String> WorkInfoIds = list.stream().map(InventoryWorkInfo::getId).collect(Collectors.toList());
        InventoryWorkAssetsParam inventoryWorkAssetsParam = new InventoryWorkAssetsParam();
        inventoryWorkAssetsParam.setInventoryWorkInfoIds(WorkInfoIds);
        List<InventoryWorkAssets> inventoryWorkAssets = workAssetsService.selectList(inventoryWorkAssetsParam);
        Map<String, List<InventoryWorkAssets>> collect = inventoryWorkAssets.stream().collect(Collectors.groupingBy(InventoryWorkAssets::getInventoryWorkInfoId));
        //计算
        for (InventoryWorkInfo inventoryWorkInfo : list) {
            List<InventoryWorkAssets>   inventoryWorkAssetsList = collect.get(inventoryWorkInfo.getId());
            if(CollUtil.isNotEmpty(inventoryWorkAssetsList)){
                int count =(int) inventoryWorkAssetsList.stream().filter(obj -> obj.getInventoryCount() == null).count();
                Map<String, Integer> status2CountMap = new LinkedHashMap<>();
                int size = inventoryWorkAssetsList.size();
                status2CountMap.put(WorkStateCountEnum.TOBE.getDesc(),count);
                status2CountMap.put(WorkStateCountEnum.INVENTORIED.getDesc(), size-count);
                status2CountMap.put(WorkStateCountEnum.TOTAL.getDesc(),size);
                inventoryWorkInfo.setStatus2CountMap(status2CountMap);
            }
        }
        return list;
    }

    @Override
    public void startInventory(InventoryAssetsIdsParam param) throws Exception {
        List<String> ids = param.getIds();
        Query query = new Query(CriteriaWrapper.where(InventoryWorkInfo::getId).in(ids));
        List<InventoryWorkInfo> infos = inventoryWorkInfoMapper.find(query);
        List<InventoryWorkInfo> collect = infos.stream().filter(info -> info.getWorkState().equals(WorkStateEnum.SUCCESS.getCode())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(collect)) {
            throw new BusinessException("completed-cannot-be-selected");
        }
        Update update = new Update();
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getWorkState), WorkStateEnum.PROCESSING.getCode());
        update.set(CMDBTool.getFieldName(InventoryWorkInfo::getActualStartTime), DateUtils.date());
        CMDBTool.updateFirst(inventoryWorkInfoMapper, query, update);
    }

    @Override
    public MWPage inventoryHistory(InventorySearchParam param) throws Exception {
        param.setWorkState(WorkStateEnum.SUCCESS.getCode());
        param.setIgnoreDataAuth(true);
        param.convert();
        param.sort();
        Criteria criteria = genCriteria(param);
        List<InventoryWorkInfo> list = CMDBTool.selectAuthorizedList(InventoryWorkInfo.class,inventoryWorkInfoMapper, criteria, param);
        List<Long> userIds = list.stream()
                .flatMap(info -> info.getPrincipal().stream().map(id -> Long.valueOf(id)))
                .collect(Collectors.toList());
        List<MwUser> usersByUserIds = userApi.getUsersByUserIds(userIds);
        Map<Long, String> userMap = usersByUserIds.stream().collect(Collectors.toMap(MwUser::getId, MwUser::getNickName));
        list.forEach(info -> {
            List<String> collect = info.getPrincipal().stream().map(principal -> userMap.get(Long.valueOf(principal)))
                    .collect(Collectors.toList());
            info.setPrincipal(collect);
        });
        MWPage pageRet = (MWPage) viewManager.getListViewObject(list, InventoryWorkInfo.class, param, new ViewConvertContext());
        return pageRet;
    }

    public List<InventoryHistoryCountDTO> inventoryHistoryCount() throws Exception {
        // 创建查询条件，查询成功且未删除的盘点任务
        Query query = new Query(CriteriaWrapper.where(InventoryWorkInfo::getWorkState).is(WorkStateEnum.SUCCESS.getCode()));
        query.addCriteria(CriteriaWrapper.where(InventoryWorkInfo::getDelFlag).is(false));
        List<InventoryWorkInfo> list = inventoryWorkInfoMapper.find(query);
        // 初始化结果列表，包含所有结果类型，初始计数为0
        List<InventoryHistoryCountDTO> resultList = new ArrayList<>();
        resultList.add(new InventoryHistoryCountDTO("ALL", list.size()));

        // 创建一个Map，初始值为0
        Map<String, Integer> resultCountMap = Arrays.stream(InventoryCheck.InventoryResultEnum.values())
                .collect(Collectors.toMap(InventoryCheck.InventoryResultEnum::getCode, e -> 0));

        // 计算实际的结果数量
        Map<String, Integer> actualCountMap = list.stream()
                .collect(Collectors.groupingBy(InventoryWorkInfo::getInventoryResult, Collectors.summingInt(e -> 1)));

        // 更新初始Map中的值
        actualCountMap.forEach(resultCountMap::put);

        // 将结果添加到结果列表中
        resultList.addAll(resultCountMap.entrySet().stream()
                .map(entry -> new InventoryHistoryCountDTO(entry.getKey(), entry.getValue()))
                .collect(Collectors.toList()));

        return resultList;
    }

    @Override
    public String delInventoryWork(InventoryIdsParam param) throws Exception {
        if(SecurityUtils.getUser().isAdmin()){
            log.info("管理员删除盘点任务成功...ids:{}", param.getIds());
            CMDBTool.remove(inventoryWorkInfoMapper, param.getIds(), InventoryWorkInfo.class, true);
            return messageSource.getMessage("delete-success",null,LocaleContextHolder.getLocale());
        }
        Query query = new Query(CriteriaWrapper.where(InventoryWorkInfo::getId).in(param.getIds()));
        List<InventoryWorkInfo> ret = CMDBTool.selectList(InventoryWorkInfo.class, inventoryWorkInfoMapper, query, null);
        // 过滤出状态为未开始或超期的任务
        List<String> ids = ret.stream()
                .filter(work -> work.getWorkState().equals(WorkStateEnum.PENDING.getCode()) || work.getWorkState().equals(WorkStateEnum.EXCEED.getCode()))
                .map(InventoryWorkInfo::getId)
                .collect(Collectors.toList());
        CMDBTool.remove(inventoryWorkInfoMapper, ids, InventoryWorkInfo.class, true);
        Update assetsMapperUpdate = new Update();
        assetsMapperUpdate.set(CMDBTool.getFieldName(InventoryWorkAssets::getDelFlag), true);
        CMDBTool.updateFirst(inventoryWorkAssetsMapper, new Query(CriteriaWrapper.where(InventoryWorkAssets::getInventoryWorkInfoId).in(ids)), assetsMapperUpdate);
        log.info("删除盘点任务成功...ids:{}", ids);
        List<InventoryWorkInfo> collect = ret.stream().filter(work -> work.getWorkState().equals(WorkStateEnum.SUCCESS.getCode()) || work.getWorkState().equals(WorkStateEnum.PROCESSING.getCode())).collect(Collectors.toList());
        if (CollUtil.isEmpty(collect)) {
            return messageSource.getMessage("delete-success", null, LocaleContextHolder.getLocale());
        }
        if (collect.size() != ret.size()) {
            return messageSource.getMessage("non-completed-cannot-be-deleted", null, LocaleContextHolder.getLocale());
        } else {
            throw new BusinessException(messageSource.getMessage("completed-or-in-progress-cannot-be-deleted", null, LocaleContextHolder.getLocale()));
        }
    }

    @Override
    public Map<String, Integer> inventoryCount(InventorySearchParam param) throws Exception {
        GroupSearchOperation groupSearchOperation = new GroupSearchOperation();
        List<Criteria> criteriaList = new ArrayList<>();
        Long userId = SecurityUtils.getUserId();
        param.setPrincipal(strValueConvert(userId));
        param.setIgnoreDataAuth(true);
        param.convert();
        param.sort();
        Criteria criteria = genCriteria(param);
        criteriaList.add(criteria);
        if(null != param.getInventoryType()){
            Criteria criteria2 = new Criteria(CMDBTool.getFieldName(InventoryWorkInfo::getInventoryType)).is(param.getInventoryType());
            criteriaList.add(criteria2);
        }
        Criteria searchCriteria = new Criteria().andOperator(criteriaList);

        //List<InventoryWorkInfo> list = CMDBTool.selectAuthorizedList(InventoryWorkInfo.class,inventoryWorkInfoMapper, searchCriteria, param);
        String groupName = CMDBTool.getFieldName(InventoryWorkInfo::getWorkState);
        groupSearchOperation.addGroupField(groupName,groupName);
        groupSearchOperation.addCalculateField(CMDBTool.getFieldName(InventoryWorkInfoStatusCountInfo::getCount), GroupCalculateMethodEnum.count, null);
        param.setGroupSearchOperation(groupSearchOperation);
        List<InventoryWorkInfoStatusCountInfo> result = CMDBTool.aggregateAuthorizedList(InventoryWorkInfoStatusCountInfo.class, inventoryWorkInfoMapper, searchCriteria, param);
        Map<String, Integer> status2CountMap = new LinkedHashMap<>();
        status2CountMap.put(WorkStateEnum.PENDING.getDesc(), 0);
        status2CountMap.put(WorkStateEnum.PROCESSING.getDesc(), 0);
        status2CountMap.put(WorkStateEnum.SUCCESS.getDesc(), 0);
        status2CountMap.put(WorkStateEnum.EXCEED.getDesc(), 0);
        if (CollectionUtils.isNotEmpty(result)) {
            Map<String, Integer> queryMap = result.stream().collect(Collectors.toMap(InventoryWorkInfoStatusCountInfo::getId, InventoryWorkInfoStatusCountInfo::getCount));
            for (Map.Entry<String, Integer> item : queryMap.entrySet()) {
                    status2CountMap.put(WorkStateEnum.getEnum(item.getKey()).getDesc(), item.getValue());
            }
        }
        return status2CountMap;
    }



}

